package cn.teawooo.log;

import java.text.MessageFormat;

/**
 * 功能描述：
 * @author teawooo <long1795@gmail.com>
 * @time 2013年8月23日 下午4:56:00
 */
public final class MessageFormatter extends MessageFormat {
    private static final long serialVersionUID = 1L;

    static final char DELIM_START = '{';
    static final char DELIM_STOP = '}';
    static final String DELIM_STR = "{}";
    static final String DELIM_STR_REX = "\\{\\}";

    /**
     * @param pattern
     */
    public MessageFormatter(String pattern) {
        super(convertPattern(pattern));
    }

    public static String convertPattern(String pattern) {
        boolean appendFlag = false;
        if (pattern.endsWith(DELIM_STR)) {
            pattern = pattern + ".";
            appendFlag = true;
        }

        String[] ps = pattern.split(DELIM_STR_REX);
        if (ps.length <= 1) {
            return pattern;
        }

        StringBuffer s = new StringBuffer(ps[0]);
        for (int i = 1; i < ps.length; i++) {
            s.append(DELIM_START).append(i - 1).append(DELIM_STOP).append(ps[i]);
        }
        if (appendFlag) {
            s.deleteCharAt(s.length() - 1);
        }
        return s.toString();
    }

    public static final String format(String pattern, Object... arguments) {
        if (arguments == null || arguments.length == 0) {
            return pattern;
        }
        MessageFormatter temp = new MessageFormatter(pattern);
        return temp.format(arguments);
    }

}
